<template>
  <div class="main-box">
    <TreeFilter
      v-if="initFlag && leftFilter"
      label="name"
      :title="leftFilterColumn.columnLabel"
      :request-api="() => getColumnDataSource({ columnId: leftFilterColumn.columnId })"
      @change="leftFilterChange"
      :multiple="leftFilterColumn.isQueryMultiple === '1'"
      :tree="leftFilterColumn.controlType.startsWith('tree') || leftFilterColumn.controlType.startsWith('cascader')"
    />
    <div class="table-box">
      <ProTable
        v-if="initFlag"
        ref="proTable"
        highlight-current-row
        @cell-click="cellClick"
        :row-key="config.primaryKey"
        :pagination="!isTreeList"
        :columns="columns"
        :request-api="getTableList"
        :init-param="initParam"
        :data-callback="dataCallback"
        @sort-change="sortChange"
        :show-summary="!isTreeList"
        :summary-method="summaryMethod"
      >
        <!-- 菜单图标 -->
        <template #icon="scope" v-if="config.modId === '2'">
          <el-icon :size="18" v-if="scope.row.icon && scope.row.icon !== '#'">
            <component :is="scope.row.icon"></component>
          </el-icon>
          <span v-else>{{ scope.row.icon }}</span>
        </template>
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button
            v-for="item in buttons"
            :key="item.code"
            :type="item.type"
            :icon="item.icon"
            :disabled="item.disabled"
            @click="buttonClick(item)"
            >{{ item.name }}</el-button
          >
        </template>
        <!-- 表格行上操作 -->
        <!-- <template #operation="scope">
          <el-button type="primary" link :icon="View" @click="openDrawer(OperatorType.view, scope.row)">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="openDrawer(OperatorType.edit, scope.row)">编辑</el-button>
          <el-button type="primary" link :icon="Delete" @click="openDrawer(OperatorType.delete, scope.row)">删除</el-button>
        </template> -->
      </ProTable>
      <detail v-if="initFlag" ref="detailRef" :mod-id="config.modId" :form-size="config.formSize" />
    </div>
  </div>
</template>

<script setup lang="tsx" name="ModManage">
import { ref, reactive, onMounted } from "vue";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import detail from "@/views/mod/data/detail.vue";
import { ProTableInstance, ColumnProps, SearchType, ButtonProps } from "@/components/ProTable/interface";
import { getModInfo, getModDataList, getModDataPage, fireModData } from "@/api/modules/mod";
import { getFlowEvent } from "@/api/modules/flow";
import { getColumnDataSource } from "@/api/modules/system";
import { OperatorType } from "@/enums/enum";
import { arrayToTree } from "@/utils";
import { Mod } from "@/api/interface/index";
import { useRoute } from "vue-router";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { computed } from "vue";
import { useTabsStore } from "@/stores/modules/tabs";
import { getListener } from "@/listeners/index";

// ProTable 实例
const proTable = ref<ProTableInstance>();
const route = useRoute();
const tabStore = useTabsStore();

// 模块初标识
const initFlag = ref(false);
const leftFilter = ref(false);
const leftFilterColumn = ref<any>({});
// 模块初配置信息
const config = reactive<Mod.SysModInfo>({
  modId: "",
  isTreeList: "0",
  isFlow: "0",
  status: "0",
  formSize: 500
});
const flowEvent = ref<any>({});
// 表格参数
const initParam = reactive({});
// 合计行数据
const summaryData = reactive({});
//是否树形表格
const isTreeList = computed(() => {
  return config.isTreeList === "1";
});
// 表格列配置项
const columns = reactive<ColumnProps<any>[]>([{ type: "index", label: "#", width: 80 }]);
//表格按钮配置项
const buttons = reactive<ButtonProps<any>[]>([]);

// dataCallback 是对于返回的表格数据做处理
const dataCallback = (data: any) => {
  if (config.isTreeList === "1") {
    const data1 = arrayToTree(data, config.primaryKey, config.pid, "0");
    return data1;
  } else {
    Object.assign(summaryData, data.summary);
    return {
      list: data.list,
      total: data.total,
      pageNum: data.pageNum,
      pageSize: data.pageSize
    };
  }
};

//排序回调方法
const sortChange = (column: any) => {
  const prop = column.prop;
  const order = column.order === "ascending" ? "asc" : column.order === "descending" ? "desc" : null;
  const sortInfo = { sortName: prop, sortBy: order };
  Object.assign(initParam, sortInfo);
};

//排序回调方法
const leftFilterChange = (val: any) => {
  initParam[leftFilterColumn.value.columnName] = val;
};

//合计行方法
const summaryMethod = params => {
  if (summaryData && Object.keys(summaryData).length > 0) {
    const sum: any = [];
    params.columns.forEach(element => {
      const prop = element.property;
      sum.push(summaryData[prop]);
    });
    sum[0] = "合计";
    return sum;
  }
  return {};
};

const initMod = async () => {
  if (initFlag.value) return;

  //先判断url如何取出标题和图标
  const modName = route.query.modName as string;
  const modIcon = route.query.modIcon as string;
  let modId = route.params.id as string;
  if (modName) {
    tabStore.setTabsTitle(`${route.query.modName}`);
  }
  if (modIcon) {
    tabStore.setTabsIcon(modIcon);
  }
  if (!modId) {
    //从url截取
    modId = route.path.substring(route.path.lastIndexOf("\/") + 1, route.path.length);
  }

  let { data } = await getModInfo({ modId: modId });
  Object.assign(config, data);
  console.log(config);
  Object.assign(initParam, { modId: modId });
};

// 初始化表格
const initTable = async () => {
  if (initFlag.value) return;

  //设置表头
  let columns1 = config.columns!.sort((a, b) => a.listColumnOrderNum - b.listColumnOrderNum);
  columns1.forEach(item => {
    const column: any = {
      prop: item.columnName,
      label: item.columnLabel,
      isShow: item.isListColumn === "1",
      width: item.listColumnWidth === 0 ? "" : item.listColumnWidth,
      sortable: config.isTreeList === "1" ? false : "custom"
    };

    //查询条件处理
    //左侧查询，只有第一个有效
    if (!leftFilter.value && item.isQueryLeft === "1") {
      leftFilter.value = true;
      leftFilterColumn.value = item;
    } else {
      column.search = item.queryType === "none" ? {} : { el: item.controlType as SearchType, order: item.queryOrderNum };
    }

    //针对是否类型的字段，处理显示方式
    if (item.columnName.startsWith("is_")) {
      column.tag = true;
      column.enum = [
        { label: "否", value: "0" },
        { label: "是", value: "1", tagType: "success" }
      ];
    }
    //针对是否类型的字段，处理显示方式
    else if (item.columnName === "status") {
      column.tag = true;
      column.enum = [
        { label: "禁用", value: "0", tagType: "danger" },
        { label: "启用", value: "1", tagType: "success" }
      ];
    }
    //针对下拉框和下拉树
    if (item.controlType.startsWith("select") || item.controlType.startsWith("tree") || item.controlType.startsWith("cascader")) {
      column.enum = () => getColumnDataSource({ columnId: item.columnId });
      column.fieldNames = { label: "name", value: "id" };
      column.multiple = item.isQueryMultiple === "1";
    }
    columns.push(column);
  });
  // 添加操作列
  // columns.push({ prop: "operation", label: "操作", fixed: "right", width: 230 });

  initFlag.value = true;
};

//初始化按钮
const initButtons = async () => {
  const btn1 = { code: "add", name: "新增", operatorType: OperatorType.ADD, type: "primary", icon: "Plus", disabled: false };
  const btn2 = { code: "edit", name: "编辑", operatorType: OperatorType.EDIT, type: "success", icon: "Edit", disabled: true };
  const btn3 = {
    code: "delete",
    name: "删除",
    operatorType: OperatorType.DELETE,
    type: "danger",
    icon: "Delete",
    disabled: true
  };
  const btn4 = { code: "view", name: "查看", operatorType: OperatorType.VIEW, type: "warning", icon: "View", disabled: true };
  // const btn5 = { code: "import", name: "导入", operatorType: OperatorType.IMPORT, type: "info", icon: "Upload", disabled: false };
  // const btn6 = {
  //   code: "export",
  //   name: "导出",
  //   operatorType: OperatorType.EXPORT,
  //   type: "info",
  //   icon: "Download",
  //   disabled: false
  // };
  const btn7 = {
    code: "config",
    name: "列配置",
    operatorType: OperatorType.CUSTOM,
    type: "primary",
    icon: "Setting",
    disabled: true
  };
  const btn8 = {
    code: "flow",
    name: "流程配置",
    operatorType: OperatorType.CUSTOM,
    type: "primary",
    icon: "Setting",
    disabled: true
  };

  if (config.isFlow === "1") {
    let { data } = await getFlowEvent({ machineId: config.machineId! });

    flowEvent.value = data;

    data.events.sort((a, b) => a.seq - b.seq);

    data.events.forEach(item => {
      const btnTemp = {
        code: item.id,
        name: item.name,
        operatorType: item.operate,
        type: item.color,
        icon: item.icon,
        disabled: true,
        seq: item.seq
      };
      if (item.selected === "0") {
        btnTemp.disabled = false;
      } else {
        btnTemp.disabled = true;
      }
      buttons.push(btnTemp);
    });
  } else {
    buttons.push(btn1);
    buttons.push(btn2);
    buttons.push(btn3);
    buttons.push(btn4);
    // buttons.push(btn5);
    // buttons.push(btn6);
    if (config.modId === "1") {
      buttons.push(btn7);
      buttons.push(btn8);
    }
  }
};

//初始化
onMounted(async () => {
  await initMod();
  await initTable();
  await initButtons();
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
const getTableList = async (params: any) => {
  proTable.value?.element?.setCurrentRow(null);
  return config.isTreeList === "1" ? getModDataList(params) : getModDataPage(params);
};

//点击单元格
const cellClick = (row: any, column: any, cell: HTMLTableCellElement, event: Event) => {
  console.log(row, column, cell, event);

  proTable.value?.element?.clearSelection();
  if (row) {
    proTable.value?.element?.toggleRowSelection(row, true);
  }

  if (config.isFlow === "1") {
    let nodeId = row.node_id;
    let nodeEvent = flowEvent.value.nodeEvents.find(y => y.id === nodeId);
    flowEvent.value.events.forEach(item => {
      item.disabled = true;
      if (item.type === "OTHER") {
        item.disabled = false;
      } else if (nodeEvent.events.some(x => x.id === item.id)) {
        item.disabled = false;
      }
      buttons.find(x => x.code === item.id)!.disabled = item.disabled;
    });
  } else {
    buttons.forEach(x => {
      x.disabled = false;
    });
  }
};

// 打开 drawer(新增、查看、编辑)
const detailRef = ref<InstanceType<typeof detail> | null>(null);

// type:查看、新增、修改、删除
const buttonClick = async (btn: ButtonProps<any>) => {
  let row: any = null; // 最后选择的数据行

  const rows = proTable.value?.selectedList;
  if (rows && rows.length > 0) {
    row = rows[rows.length - 1];
  }
  if (btn.operatorType === OperatorType.ADD) {
    //左侧也带入默认值
    row = {};
    if (leftFilter.value) {
      row[leftFilterColumn.value.columnName] = initParam[leftFilterColumn.value.columnName];
    }
  }

  let listener = getListener(config.modId);
  if (listener && listener.before) {
    let r = await listener.before(config.modId, btn, row);
    if (!r) {
      return;
    }
  }

  if (
    btn.operatorType === OperatorType.DELETE ||
    btn.operatorType === OperatorType.SUBMIT ||
    btn.operatorType === OperatorType.BACK
  ) {
    const fireInfo: Mod.FireInfo = {
      modId: config.modId,
      machineId: config.machineId!,
      eventId: btn.code,
      instanceId: row.instance_id,
      data: row
    };
    await useHandleData(fireModData, fireInfo, `${btn.name}【${row[config.primaryKey!]}】${config.modName}`);

    if (listener && listener.after) {
      let r = listener.after(config.modId, btn, row);
      if (!r) {
        return;
      }
    }

    proTable.value?.getTableList();
    return;
  } else if (btn.operatorType === OperatorType.CUSTOM) {
    if (listener && listener.after) {
      let r = await listener.after(config.modId, btn, row);
      if (!r) {
        return;
      }
    }

    proTable.value?.getTableList();
    return;
  }

  // 其他按钮事件
  const params = {
    title: btn.name + config.modName,
    btn: btn,
    row: row,
    getTableList: proTable.value?.getTableList
  };
  console.log(params);
  detailRef.value?.acceptParams(params);
};
</script>
